package og.example.dao;
import og.example.entity.Student;
import og.example.entity.Group;
import java.util.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class StudentDataProvider {
    private static AtomicInteger studentIdGenerator = new AtomicInteger(0);
    private static List<Student> students = new CopyOnWriteArrayList<>();

    public static boolean studentAdd(Long studentId, String studentName, String groupName) {
        if (students.stream().anyMatch(student -> student.getStudentId().equals(studentId))) {
            return false; // 学生ID已存在
        }
        GroupDataProvider.incrementStudentCountForGroup(groupName); // 更新小组的学生数量
        Student newStudent = new Student(studentIdGenerator.incrementAndGet(), studentId, studentName, groupName);
        students.add(newStudent);
        return true;
    }

    public static boolean studentDelete(Long studentId) {
        for (Student student : students) {
            if (student.getStudentId().equals(studentId)) {
                GroupDataProvider.decrementStudentCountForGroup(student.getGroupName());
                students.remove(student);
                return true;
            }
        }
        return false;
    }
    public static Student getRandomStudent() {
        if (students.isEmpty()) {
            return null;
        }
        int index = (int) (Math.random() * students.size());
        return students.get(index);
    }

    public static List<Student> studentQuery() {
        return new ArrayList<>(students);
    }
}